//
//  AppDelegate.m
//  HeartBeat
//
//  Created by karong on 2023/8/23.
//

#import "AppDelegate.h"
#import "HBBaseTabBarController.h"
#import "FirebaseCore.h"
#import "Firebase.h"
#import "IQKeyboardManager.h"
#import <FBSDKCoreKit/FBSDKCoreKit.h>
#import <FBSDKLoginKit/FBSDKLoginKit.h>
#import <AppTrackingTransparency/AppTrackingTransparency.h>
#import <AppsFlyerLib/AppsFlyerLib.h>
@import LineSDK;

@interface AppDelegate () <AppsFlyerLibDelegate>

@end

@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [FIRApp configure];
    [self initLine];
    [self initAppsFlyer];
    [self createFaceBook:application didFinishLaunchingWithOptions:launchOptions];
    [self initIQKeyboardManager];
    [self initMainPage];
    [self loadConfig];
    return YES;
}
- (void)initLine {
//    [ShareSDK registPlatforms:^(SSDKRegister *platformsRegister) {
//        [platformsRegister setupLineAuthType:SSDKAuthorizeTypeBoth];
//    }];
    [[LineSDKLoginManager sharedManager] setupWithChannelID:HB_LINE_ID universalLinkURL:nil];
}

- (void)initIQKeyboardManager {
    IQKeyboardManager *keyboardManager = [IQKeyboardManager sharedManager];
    keyboardManager.enable = YES;
    keyboardManager.shouldResignOnTouchOutside = YES;
    keyboardManager.enableAutoToolbar = NO;
    keyboardManager.keyboardDistanceFromTextField = 61 + 12;
    [keyboardManager registerTextFieldViewClass:[YYTextView class] didBeginEditingNotificationName:YYTextViewTextDidBeginEditingNotification didEndEditingNotificationName:YYTextViewTextDidEndEditingNotification];
}

/// 初始化facebook
- (void)createFaceBook:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [FBSDKSettings setAdvertiserTrackingEnabled:YES];
    FBSDKSettings.autoLogAppEventsEnabled = YES;
    BOOL s = [[FBSDKApplicationDelegate sharedInstance] application:application didFinishLaunchingWithOptions:launchOptions];
    NSLog(@"ddddd====%d",s);

    //设置延迟深度链接
        if (launchOptions[UIApplicationLaunchOptionsURLKey] == nil) {
            [FBSDKAppLinkUtility fetchDeferredAppLink:^(NSURL *url, NSError *error) {
                if (error) {
                    NSLog(@"Received error while fetching deferred app link %@", error);
                }
                if (url) {
                    //延时一秒钟启動深度連接
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:^(BOOL success) {
                        }];
                    });
                }
            }];
        }
}

- (void)initAppsFlyer {
    // AppsFlyer
    [AppsFlyerLib shared].appsFlyerDevKey = HB_FLYER_KEY;
    [AppsFlyerLib shared].appleAppID = HB_APPSTORY_ID;
    [AppsFlyerLib shared].delegate = self;
    if (@available(iOS 14, *)) {
        [[AppsFlyerLib shared] waitForATTUserAuthorizationWithTimeoutInterval:60];
    }
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(sendLaunch:) name:UIApplicationDidBecomeActiveNotification object:nil];
}

- (void)sendLaunch:(UIApplication *)application {
    [[AppsFlyerLib shared] start];
}

- (void)initMainPage {
    UIViewController *mainVC;
    if(appUserCenter.isLogin) {
        [self getUserInfoRequest];
        HBBaseNavigationController * nav = [[HBBaseNavigationController alloc]initWithRootViewController:[HBBaseTabBarController new]];
        nav.navigationBarHidden = YES;
        mainVC = nav;
    }
    else {
        HBBaseNavigationController * nav = [[HBBaseNavigationController alloc]initWithRootViewController:[ViewManager loginVC]];
        nav.navigationBarHidden = YES;
        mainVC = nav;
    }
    self.window.rootViewController = mainVC;
}

- (void)reloadMain {
//    [self initMainPage];
    UIViewController * vc = self.window.rootViewController;
    if ([vc isKindOfClass:NSClassFromString(@"HBBaseNavigationController")]) {
        HBBaseNavigationController * nav = self.window.rootViewController;
        vc = nav.viewControllers.firstObject;
        UIViewController *mainVC;
        if ([vc isKindOfClass:NSClassFromString(@"HBBaseTabBarController")]) {
            HBBaseNavigationController * nav = [[HBBaseNavigationController alloc]initWithRootViewController:[HBBaseTabBarController new]];
            nav.navigationBarHidden = YES;
            mainVC = nav;
        }
        else {
            HBBaseNavigationController * nav = [[HBBaseNavigationController alloc]initWithRootViewController:[ViewManager loginVC]];
            nav.navigationBarHidden = YES;
            mainVC = nav;
        }
        self.window.rootViewController = mainVC;
    }
    [self.window makeKeyAndVisible];
}

- (void)loadConfig {
    [HBRequest 获取启动配置];
}

- (void)getUserInfoRequest {
    [appUserCenter getUserInfoRequest];
}
#pragma mark - UISceneSession lifecycle
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options{
    [[FBSDKApplicationDelegate sharedInstance]application:app openURL:url options:options];
    [[LineSDKLoginManager sharedManager] application:app open:url options:options];
    return YES;
}

- (void)applicationDidBecomeActive:(UIApplication *)application{
    [FBSDKAppEvents activateApp];
    if (@available(iOS 14, *)) {
        //申请权限
        [ATTrackingManager requestTrackingAuthorizationWithCompletionHandler:^(ATTrackingManagerAuthorizationStatus status) {
            if (status == ATTrackingManagerAuthorizationStatusAuthorized){
                [FBSDKSettings setAdvertiserTrackingEnabled:YES];
            }else{
                [FBSDKSettings setAdvertiserTrackingEnabled:NO];
            }
        }];
    }
}
@end
